package com.xc.service;

import com.xc.helloworld.HandlerClientHello;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Package com.xc.service
 * @Description Netty服务端启动类
 * @Author kunshan
 * @Date 2021/1/27 11:41 上午
 */
public class NettyServer {
    private static final int  port = 6789;  //设置服务器端口
    private static EventLoopGroup group = new NioEventLoopGroup();//通过NIO方式来接收链接和处理链接
    private static ServerBootstrap b = new ServerBootstrap();

    /**
     * Netty创建全部是实现自AbstractBootstrap
     * 客户端的是Boostrap，服务端则是 ServerBootstrap
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        try {
            b.group(group);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new NettyServerFilter()); //添加自定义的handler
            // 配置完成);//设置过滤器
            //服务器绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务端启动成功");
            //监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
